import { CheckCircleOutlined } from '@ant-design/icons';
import { ProForm } from '@ant-design/pro-components';
import { Button } from 'antd';
import { NamePath } from 'antd/es/form/interface';
import { useState } from 'react';
import wait from 'wait';

export function DataAdd<DataType extends object>(props: {
  baseName: NamePath;
  onConfirm: (data: DataType) => void;
  children: (params: {
    addBaseName(name: NamePath): string[];
  }) => React.ReactNode;
}) {
  const { children, baseName } = props;
  const data = ProForm.useWatch(baseName);
  const form = ProForm.useFormInstance();
  async function onConfirm() {
    const hasError = await form
      .validateFields()
      .then((res) => false)
      .catch((error) => true);
    if (hasError) return;
    setStatus(Status.LOADING);
    await wait(500);
    setStatus(Status.SUCCESS);
    await wait(500);
    setStatus(Status.NORMAL);
    props.onConfirm(data);
  }

  const [status, setStatus] = useState<Status>(Status.NORMAL);

  return (
    <>
      <div
        onBlur={(e) => {
          // stop submit
          e.stopPropagation();
        }}
      >
        {children({ addBaseName: (name) => [...baseName, name] })}
      </div>
      <Button
        block
        type="primary"
        ghost
        onClick={onConfirm}
        loading={status === Status.LOADING}
        icon={status === Status.SUCCESS && <CheckCircleOutlined />}
      >
        {status === Status.NORMAL && '确认添加'}
      </Button>
    </>
  );
}

enum Status {
  NORMAL = 'normal',
  LOADING = 'loading',
  SUCCESS = 'success',
}
